<template>
  <div class="service-management">
    <!-- 搜索条件 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="服务名称" prop="serviceName">
          <el-input
            v-model="queryParams.serviceName"
            placeholder="请输入服务名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="服务代码" prop="serviceCode">
          <el-input
            v-model="queryParams.serviceCode"
            placeholder="请输入服务代码"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择服务状态" clearable style="width: 200px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用分要求" prop="requiredScore">
          <el-select v-model="queryParams.requiredScore" placeholder="请选择信用分要求" clearable style="width: 200px">
            <el-option label="无要求" value="0" />
            <el-option label="650分以上" value="650" />
            <el-option label="700分以上" value="700" />
            <el-option label="750分以上" value="750" />
            <el-option label="800分以上" value="800" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="table-card" shadow="never">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleSyncData"
          >同步数据</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 服务配置列表表格 -->
      <el-table
        v-loading="loading"
        :data="serviceList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="服务ID" prop="configId" width="80" />
        <el-table-column label="服务名称" prop="serviceName" width="180" show-overflow-tooltip />
        <el-table-column label="服务代码" prop="serviceCode" width="120" show-overflow-tooltip />
        <el-table-column label="信用分要求" prop="requiredScore" width="120" align="center" sortable="custom">
          <template slot-scope="scope">
            <span v-if="scope.row.requiredScore > 0">{{ scope.row.requiredScore }}分</span>
            <span v-else class="text-muted">无要求</span>
          </template>
        </el-table-column>
        <el-table-column label="服务描述" prop="serviceDesc" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改服务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务代码" prop="serviceCode">
              <el-input v-model="form.serviceCode" placeholder="请输入服务代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务描述" prop="serviceDesc">
          <el-input
            v-model="form.serviceDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入服务描述"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信用分要求" prop="requiredScore">
              <el-input-number
                v-model="form.requiredScore"
                :min="0"
                :max="850"
                :step="10"
                placeholder="请输入信用分要求"
                style="width: 100%"
              />
              <div class="form-tip">设置为0表示无信用分要求</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="'0'">正常</el-radio>
                <el-radio :label="'1'">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="指导图片" prop="guideImages">
          <el-input
            v-model="form.guideImages"
            type="textarea"
            :rows="2"
            placeholder="请输入指导图片链接（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 服务详情对话框 -->
    <el-dialog title="服务详情" :visible.sync="detailDialogVisible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="服务ID">{{ currentService.configId }}</el-descriptions-item>
        <el-descriptions-item label="服务名称">{{ currentService.serviceName }}</el-descriptions-item>
        <el-descriptions-item label="服务代码">{{ currentService.serviceCode }}</el-descriptions-item>
        <el-descriptions-item label="信用分要求">
          <span v-if="currentService.requiredScore > 0">{{ currentService.requiredScore }}分</span>
          <span v-else>无要求</span>
        </el-descriptions-item>
        <el-descriptions-item label="服务描述" :span="2">{{ currentService.serviceDesc }}</el-descriptions-item>
        <el-descriptions-item label="指导图片" :span="2">{{ currentService.guideImages }}</el-descriptions-item>
        <el-descriptions-item label="服务状态">
          <el-tag :type="currentService.status === '0' ? 'success' : 'danger'" size="small">
            {{ currentService.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(currentService.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ parseTime(currentService.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentService.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getServiceConfigList, getServiceConfig, addServiceConfig, updateServiceConfig, delServiceConfig, batchUpdateServiceStatus, syncServiceData } from '@/api/credit/admin'

export default {
  name: 'CreditServiceManagement',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务配置表格数据
      serviceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: null,
        serviceCode: null,
        status: null,
        requiredScore: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceCode: [
          { required: true, message: '服务代码不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '服务代码长度在2到50个字符', trigger: 'blur' }
        ],
        serviceName: [
          { required: true, message: '服务名称不能为空', trigger: 'blur' },
          { min: 2, max: 100, message: '服务名称长度在2到100个字符', trigger: 'blur' }
        ],
        serviceDesc: [
          { required: true, message: '服务描述不能为空', trigger: 'blur' },
          { min: 10, max: 500, message: '服务描述长度在10到500个字符', trigger: 'blur' }
        ],
        requiredScore: [
          { type: 'number', min: 0, max: 850, message: '信用分要求范围为0-850', trigger: 'blur' }
        ]
      },
      // 服务详情对话框
      detailDialogVisible: false,
      currentService: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询服务配置列表 */
    getList() {
      this.loading = true
      getServiceConfigList(this.queryParams).then(response => {
        this.serviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        configId: null,
        serviceCode: null,
        serviceName: null,
        serviceDesc: null,
        requiredScore: 0,
        guideImages: null,
        status: "0",
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 排序变化处理 */
    handleSortChange(sort) {
      if (sort.prop === 'requiredScore') {
        this.queryParams.orderByColumn = 'required_score'
        this.queryParams.isAsc = sort.order === 'ascending' ? 'asc' : 'desc'
        this.getList()
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加服务配置'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const configId = row.configId || this.ids
      getServiceConfig(configId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改服务配置'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.configId != null) {
            updateServiceConfig(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addServiceConfig(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row.configId || this.ids
      this.$modal.confirm('是否确认删除服务配置编号为"' + configIds + '"的数据项？').then(function() {
        return delServiceConfig(configIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.serviceName + '"服务吗？').then(function() {
        return batchUpdateServiceStatus({
          configIds: [row.configId],
          status: row.status
        })
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    /** 查看详情 */
    handleDetail(row) {
      this.currentService = { ...row }
      this.detailDialogVisible = true
    },
    /** 同步数据 */
    handleSyncData() {
      this.$modal.confirm('确认要同步服务数据吗？此操作将从外部系统同步最新的服务信息。').then(() => {
        this.loading = true
        return syncServiceData()
      }).then(() => {
        this.$modal.msgSuccess('同步成功')
        this.getList()
      }).catch(() => {}).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.service-management {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .mb8 {
      margin-bottom: 8px;
    }
  }

  .text-muted {
    color: #909399;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style>
